package com.fingard.dsp.bank.directbank.payfree01;

import com.fingard.constant.Format;
import com.fingard.crypto.DigestHelper;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.DirectHelper;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.text.StringHelper;

import java.io.*;
import java.math.BigDecimal;

//import fingard.net.ConnState;

public class PAYFREE01BatPayRec extends PAYFREE01Base implements IBatPayRec {
    //1988
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return d_BatPayRec(p_req1988);
    }

    //9188
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return d_BatPayRec(p_req9188);
    }

    //批量代收和批量代付提交
    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
        //返回ATS的对象
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        try {

            ActSetItem actItem = getBankConfig().getActSetItem(p_reqBat.ownAct, "bat");
            if (actItem == null) {
                retAts.respCode = "0";
                retAts.respInfo = "未找到账号" + p_reqBat.ownAct + "的批量商户配置节点";
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = "E9981";
                retAts.writeRetToATS();
                return retAts;
            }
            //#start变量
            String strFileName = "";
            //String strMerCode = actItem.merchantId;//商户号
            String strType = actItem.batType;//类型
            //String strArea = "";
            //String strBankCode = "";
            //String strDirectAccessCode = "";
            //String strAccount = "";//区域，银行代码，直连线路代码

            //strBankCode = p_reqBat.ownBankCode;
            //strDirectAccessCode = p_reqBat.reqHeader.bankCode;
            //int tmpTotalCount = p_reqBat.getTotalNum();
            String tmpTotalAmount = Format.DecimalAmtFormat.format(p_reqBat.getTotalAmt());

            //String strReqBatchNo = p_reqBat.reqBatchNO;//支付批号
            char strFillChar = ' ';//填充字符
            String thisDayBatchNo = "";//当日批次号


            //string trDate = TransSeqID.Substring(0,8);
            String trDate = Format.Date8Format.format(p_reqBat.getPayDateTime());//请求日期为当天，格式yyyyMMdd
            String dataDir = this.getDataFileDirectory(p_reqBat.getPayDateTime());

            File fileDir = new File(dataDir);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            /*
            int maxBatch = 1;
            if(fileDir.exists()){
            	File[] files = fileDir.listFiles();
            	for(int i=0;i<files.length;i++){
            		if(!files[i].getName().endsWith(".md5")){//md5文件不计入
            			maxBatch++;
            		}
            	}
            }
            else{
            	fileDir.mkdirs();
            }
            */


            int maxBatch = getBankConfig().getValueAsInt("batSeqBeginWith");
            if (maxBatch == -1) {
                maxBatch = 1;
            }
            StringBuilder sbLog = new StringBuilder();
            int countSeq = DirectHelper.countReqSeqIDMapping(p_reqBat.reqHeader.bankCode, p_reqBat.getPayDateOnly(), sbLog);
            if (countSeq < 0) {
                retAts.respCode = "0";
                retAts.respInfo = sbLog.toString();
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;
                retAts.writeRetToATS();
                return retAts;
            }
            maxBatch += countSeq;
            //maxBatch++;

            thisDayBatchNo = String.format("%02d", maxBatch);
            //#end

            //#start 文件头部
            String strPayOrRec = "";//收付标志

            //strArea = p_reqBat.ownArea;
            //strAccount = p_reqBat.ownAct;
            //文件首行：批量请求日期（8）+当日批次号（2）+代收笔数（5）+代收金额（20）+代付笔数（5）+代付金额（20）+批量回盘日期（8n）
            StringBuilder tmpSbHeadContent = new StringBuilder();
            if (p_reqBat.reqHeader.transType.equals("1988")) {
                strPayOrRec = "C";//代付
                tmpSbHeadContent.append(trDate + thisDayBatchNo + StringHelper.padLeftGBKByte("", 5, '0') + StringHelper.padLeftGBKByte("", 20, '0') + StringHelper.padLeftGBKByte(p_reqBat.totalNum, 5, '0') + StringHelper.padLeftGBKByte(tmpTotalAmount.replace(".", ""), 20, '0') + StringHelper.padLeftGBKByte("", 8, strFillChar));
            } else if (p_reqBat.reqHeader.transType.equals("9188")) {
                strPayOrRec = "D";//代收
                tmpSbHeadContent.append(trDate + thisDayBatchNo + StringHelper.padLeftGBKByte(p_reqBat.totalNum, 5, '0') + StringHelper.padLeftGBKByte(tmpTotalAmount.replace(".", ""), 20, '0') + StringHelper.padLeftGBKByte("", 5, '0') + StringHelper.padLeftGBKByte("", 20, '0') + StringHelper.padLeftGBKByte("", 8, strFillChar));
            }
            tmpSbHeadContent.append("\r\n");
            //文件名：商户号（1）+类型（2）+自定义（4）+自定义（4）+日期（8）+发送批次号（2）
            //strFileName = strMerCode + strType + DSP.Common.Common.MakeSpace(strBankCode, 4, strFillChar, "RIGHT") + DSP.Common.Common.MakeSpace(strArea, 4, strFillChar, "RIGHT") + DateTime.Now.ToString("yyyyMMdd") + thisDayBatchNo;
            //String customDefined = "";
            //if(p_reqBat.reqBatchNO.length()>8){
            //	customDefined = p_reqBat.reqBatchNO.substring(p_reqBat.reqBatchNO.length()-8, p_reqBat.reqBatchNO.length());
            //}
            //else{
            //	customDefined = StringHelper.padLeftGBKByte(p_reqBat.reqBatchNO, 8, '0');
            //}
            strFileName = strType + StringHelper.padRightGBKByte(p_reqBat.ownAct, 9, '9') + trDate + thisDayBatchNo;
            sbLog = new StringBuilder();
            boolean saved = DirectHelper.saveReqSeqIDMapping(p_reqBat.reqHeader.bankCode, p_reqBat.reqHeader.transType, p_reqBat.getPayDateOnly(), p_reqBat.reqBatchNO, strFileName, sbLog);
            if (!saved) {
                retAts.respCode = "0";
                retAts.respInfo = sbLog.toString();
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;
                retAts.writeRetToATS();
                return retAts;
            }
            //#end

            //#start 组文件内容
            String strPayOrRecFileExtend = "";
            String tmpFullPath = fileDir + File.separator + strFileName + strPayOrRecFileExtend;
            File tmpFile = new File(tmpFullPath);
            //FileWriter tmpFileWriter = null;
            PrintWriter tmpWriter = null;
            try {
                tmpFile.createNewFile();
                //tmpFileWriter = new FileWriter(tmpFile);
                tmpWriter = new PrintWriter(tmpFullPath, getCharset());
                tmpWriter.print(tmpSbHeadContent.toString());
                int intTotalNum = p_reqBat.getTotalNum();
                int rdCount = 0;
                while (p_reqBat.readRecord()) {
                    //#start 每一行
                    rdCount++;
                    String strAskNumber = "";//原银联流水
                    String strBank = "";//收/付银行代码
                    String strCNAPS = "";//收/付账号开户行联行行号 105584000001
                    String strAreaCode = "";//收/付根据地区代码表填写，默认584000
                    String strBankName = "";//收/付款人开户行名称
                    String strActType = "00";//收款人银行账号类型 00银行卡 01存折 02 信用卡
                    if (p_reqBat.readedDetail.cardType.equals("1")) {
                        strActType = "01";
                    } else if (p_reqBat.readedDetail.cardType.equals("3")) {
                        strActType = "02";
                    }
                    String strIsPrivate = "0";//账户公私类型 0私人1公司
                    if (p_reqBat.readedDetail.isPrivate.equals("1")) {
                        strIsPrivate = "0";
                    } else {
                        strIsPrivate = "1";
                    }
                    String strAccountNumber = "";//收/付款账号
                    String strAccountName = "";//收/付款账号户名
                    String strOpenCertiType = "0";//证件开户类型
                    String strOpenCertiNum = "";//证件开户号
                    String douAmount = "";
                    String strCurrency = "";

                    String strInfo = p_reqBat.readedDetail.purpose;//业务信息
                    String strDes = p_reqBat.readedDetail.memo;//备注

                    strAskNumber = p_reqBat.readedDetail.askNumber;
                    if (p_reqBat.reqHeader.transType.equals("1988")) {
                        strBank = p_reqBat.readedDetail.recBankCode;
                        strAreaCode = p_reqBat.readedDetail.recArea;

                        strAccountNumber = p_reqBat.readedDetail.recAct;
                        strAccountName = p_reqBat.readedDetail.recName;
                    } else if (p_reqBat.reqHeader.transType.equals("9188")) {
                        strBank = p_reqBat.readedDetail.payBankCode;
                        strAreaCode = p_reqBat.readedDetail.payArea;

                        strAccountNumber = p_reqBat.readedDetail.payAct;
                        strAccountName = p_reqBat.readedDetail.payName;
                    }
                    strBankName = p_reqBat.readedDetail.getOppBankLocation();
                    strCNAPS = p_reqBat.readedDetail.cnapsCode;
                    if (strCNAPS != null && strCNAPS.length() > 0) {
                        strBank = strCNAPS;
                    }
                    if (strBank != null && strBank.length() > 8) {
                        strBank = strBank.substring(0, 8);
                    }
                    //证件类型
                    //add on 2013.05.15
                    strOpenCertiType = getBankConfig().getMapValueByKey("certType", p_reqBat.readedDetail.certType);
                    if (StringHelper.isNullOrEmpty(strOpenCertiType)) {
                        strOpenCertiType = "X";
                    }

                    strOpenCertiNum = p_reqBat.readedDetail.certNum;
                    douAmount = Format.DecimalAmtFormat.format(new BigDecimal(p_reqBat.readedDetail.payAmount));
                    strCurrency = getBankConfig().getMapValueByKey("currencyMapping", p_reqBat.readedDetail.getOppCur());

                    strInfo = p_reqBat.readedDetail.useType;
                    strDes = p_reqBat.readedDetail.purpose;
                    StringBuilder sbContent = new StringBuilder();
                    sbContent.append(StringHelper.padRightGBKByte(strAskNumber, 32, strFillChar));
                    sbContent.append(StringHelper.padRightGBKByte(strBank, 8, strFillChar));
                    sbContent.append(StringHelper.padRightGBKByte(strCNAPS, 12, strFillChar));
                    sbContent.append(StringHelper.padRightGBKByte(strAreaCode, 6, strFillChar));
                    sbContent.append(StringHelper.padRightGBKByte(strBankName, 100, strFillChar));
                    sbContent.append(StringHelper.padRightGBKByte(strActType, 2, strFillChar));
                    sbContent.append(strIsPrivate);
                    sbContent.append(StringHelper.padRightGBKByte(strAccountNumber, 30, strFillChar));
                    sbContent.append(StringHelper.padRightGBKByte(strAccountName, 60, strFillChar));
                    sbContent.append(strOpenCertiType);
                    sbContent.append(StringHelper.padRightGBKByte(strOpenCertiNum, 30, strFillChar));
                    sbContent.append(StringHelper.padLeftGBKByte(douAmount.replace(".", ""), 15, '0'));
                    sbContent.append(StringHelper.padLeftGBKByte(strCurrency, 3, strFillChar));
                    sbContent.append(strPayOrRec);
                    sbContent.append(StringHelper.padRightGBKByte(strInfo, 32, strFillChar));
                    sbContent.append(StringHelper.padRightGBKByte(strDes, 30, strFillChar));
                    sbContent.append(StringHelper.padRightGBKByte("", 131, strFillChar));
                    //sbContent.append(StringHelper.padRightGBKByte("", 131, ' ') + " \r\n");
                    if (rdCount < intTotalNum) {
                        sbContent.append("\r\n");
                    }
                    tmpWriter.print(sbContent.toString());
                    //#end
                }
                tmpWriter.flush();
                tmpWriter.close();
                tmpWriter = null;
                //tmpFileWriter.close();
                //tmpFileWriter = null;
                this.WriteBankLogStep2("见数据文件" + tmpFullPath);
            } catch (Exception ex) {
                retAts.respCode = "0";
                retAts.respInfo = "生成数据文件发生异常：" + ex.getMessage();
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = "E1301";

            } finally {
                if (tmpWriter != null) {
                    tmpWriter.close();
                }
                //if(tmpFileWriter != null){
                //	tmpFileWriter.close();
                //}
            }
            //#end
            if (retAts.transState != null && retAts.transState.equals(PaymentState.FAIL_Batch)) {
                if (tmpFile.exists()) {
                    this.WriteBankLogLn("删除" + tmpFullPath);
                    tmpFile.delete();
                }
                retAts.writeRetToATS();
                return retAts;
            }
            String tmpMD5File = tmpFullPath + ".md5";
            FileOutputStream outStream = null;
            try {
                byte[] bytesMD5 = DigestHelper.cryptoMD5FromFile(tmpFullPath);
                System.out.println(StringHelper.bytesToHexString(bytesMD5));
                outStream = new FileOutputStream(tmpMD5File);
                outStream.write(bytesMD5);
            } catch (Exception ex) {
                retAts.respCode = "0";
                retAts.respInfo = "产生MD5文件失败：" + ex.getMessage();
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = "E1301";

                if (tmpFile.exists()) {
                    this.WriteBankLogLn("删除" + tmpFullPath);
                    tmpFile.delete();
                }
                retAts.writeRetToATS();
                return retAts;
            } finally {
                if (outStream != null) {
                    outStream.close();
                }
            }

            try {
                String indexDir = this.getDataIndexDir(p_reqBat.getPayDateTime());
                String indexFile = indexDir + File.separator + p_reqBat.reqBatchNO + ".txt";
                this.WriteBankLogLn("写索引文件：" + indexFile);
                FileHelper.writeFile(indexFile, strFileName, getCharset());
            } catch (Exception ex) {
                retAts.respCode = "0";
                retAts.respInfo = "写入索引文件发生异常：" + ex.getMessage();
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = "E1301";
            }

            if (retAts.transState != null && retAts.transState.equals(PaymentState.FAIL_Batch)) {
                if (tmpFile.exists()) {
                    this.WriteBankLogLn("删除" + tmpFullPath);
                    tmpFile.delete();
                }
                retAts.writeRetToATS();
                return retAts;
            }

            //#start ftp上传
            FtpSet ftpSet = bankFront.getFtpSet("bat");
            this.WriteBankLogLn("FTP上传地址" + ftpSet.serverIP + ":" + ftpSet.port);
            this.WriteBankLogLn(tmpFullPath + "FTP上传至" + ftpSet.upDir + "/" + strFileName + strPayOrRecFileExtend);
            FtpPortClient ftpPtClient = new FtpPortClient(ftpSet);
            FtpReceiver tmpReceiver = ftpPtClient.uploadFile(tmpFullPath, strFileName + strPayOrRecFileExtend);


            if (tmpReceiver.connState.length() == 0 && tmpReceiver.isCompleted) {
                retAts.respCode = "0";
                retAts.respInfo = "文件已上送服务器";
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = "Submited";
                retAts.payInfoCode = retAts.transState;

                this.WriteBankLogLn(tmpFullPath + "已上传成功");

                this.WriteBankLogLn(tmpMD5File + "FTP上传至" + ftpSet.upDir + "/" + strFileName + strPayOrRecFileExtend + ".md5");
                FtpReceiver bkUpMD5 = ftpPtClient.uploadFile(tmpMD5File, strFileName + strPayOrRecFileExtend + ".md5");
                if (bkUpMD5.connState.length() == 0 && bkUpMD5.isCompleted) {
                    this.WriteBankLogLn(tmpMD5File + "已上传成功");
                } else if (bkUpMD5.connState.equals(ConnState.FAIL)) {
                    this.WriteBankLogLn(tmpMD5File + "上传失败：" + bkUpMD5.connMsg);
                } else {
                    this.WriteBankLogLn(tmpMD5File + "上传异常：" + bkUpMD5.connMsg);
                }
            } else if (tmpReceiver.connState.equals(ConnState.FAIL)) {
                retAts.respCode = "0";
                retAts.respInfo = tmpReceiver.connMsg;
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = tmpReceiver.connState;
                if (tmpFile.exists()) {
                    this.WriteBankLogLn("删除" + tmpFullPath);
                    tmpFile.delete();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpReceiver.connMsg;
            }
            ftpPtClient.disconnect();
            //#end

        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            e.printStackTrace();
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_reqBat.reqBatchNO;
        }
        retAts.writeRetToATS();
        return retAts;
    }

    //1998 状态查询
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return d_QryBatPayRec(p_req1998);
    }

    //9198
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return d_QryBatPayRec(p_req9198);
    }

    //批量代收和批量代付状态查询
    public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
        //返回ATS的对象
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        retAts.respCode = "";


        String oriFileName = "";
        String toBankSeq = DirectHelper.getReqSeqIDMapping(p_reqQryBat.reqBatchNO);
        if (StringHelper.hasAnyChar(toBankSeq)) {
            oriFileName = toBankSeq;
        } else {
            String indexDir = this.getDataIndexDir(p_reqQryBat.getBgnDateTime());
            String indexFile = indexDir + File.separator + p_reqQryBat.reqBatchNO + ".txt";
            this.WriteBankLogLn("读取索引文件：" + indexFile);
            oriFileName = FileHelper.readFileText(indexFile, getCharset());
            this.WriteBankLogLn("读取内容：" + oriFileName);
        }
        String downFileName = oriFileName + ".rpy";

        String saveLocalFile = this.getTempFileDirectory() + File.separator + p_reqQryBat.reqBatchNO + "." + tempTransID.getNextIDStr() + ".rpy";
        FtpSet ftpSet = bankFront.getFtpSet("bat").clone();
        this.WriteBankLogLn("FTP下载地址" + ftpSet.serverIP + ":" + ftpSet.port);
        this.WriteBankLogLn("FTP下载文件" + ftpSet.downDir + "/" + downFileName + "至本地文件" + saveLocalFile);
        FtpPortClient ftpPtClient = new FtpPortClient(ftpSet);
        FtpReceiver tmpReceiver = ftpPtClient.downloadFile(downFileName, saveLocalFile);
        ftpPtClient.disconnect();
        //模拟
        //tmpReceiver.connState = "";
        //tmpReceiver.isCompleted=true;
        //saveLocalFile = "D:\\Workspaces\\FilesForDevelop\\BankPort\\PAYFREE01\\2016-09-01_安邦\\16090100582181.00003.rpy";
        //
        if (tmpReceiver.connState.length() == 0 && tmpReceiver.isCompleted) {
            retAts.respCode = "0";
            retAts.reqSeqID = p_reqQryBat.reqBatchNO;
            retAts.writeBeforeDetail();

            FileInputStream fileStream = null;
            InputStreamReader reader = null;
            BufferedReader lineReader = null;
            try {
                fileStream = new FileInputStream(saveLocalFile);
                reader = new InputStreamReader(fileStream, getCharset());
                lineReader = new BufferedReader(reader);
                String lineTxt = null;
                int lineCount = 0;
                while ((lineTxt = lineReader.readLine()) != null) {
                    lineCount++;
                    byte[] strCons = lineTxt.getBytes(getCharset());
                    if (strCons.length == 494) {
                        RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                        String strRepCode = new String(strCons, 363, 7, getCharset()).trim();//处理返回码 S：成功， F：失败
                        String strPayInfoCode = new String(strCons, 363, 7, getCharset()).trim();//支付信息吗
                        String strConsult = new String(strCons, 370, 16, getCharset()).trim();//系统参考号
                        String strMsg = new String(strCons, 386, 100, getCharset()).trim();
                        //String strTradeDate = new String(strCons, 486, 8, getCharset()).trim();
                        String strAskNumber = new String(strCons, 0, 32, getCharset()).trim();//支付流水号

                        tmpRetDetail.postScript = strAskNumber;
                        tmpRetDetail.usage = strConsult;
                        tmpRetDetail.result = strRepCode;//支付状态码 0000 交易成功
                        tmpRetDetail.payInfoCode = strPayInfoCode;//支付信息吗
                        tmpRetDetail.memo = strMsg;//支付信息

                        retAts.writeRetDetail(tmpRetDetail);
                    } else if (lineCount > 1 && strCons.length > 2) {
                        WriteBankLogLn("第" + lineCount + "行内容字节长度不符合预期：" + lineTxt);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (lineReader != null) {
                    lineReader.close();
                }
                if (reader != null) {
                    reader.close();
                }
                if (fileStream != null) {
                    fileStream.close();
                }
            }

        } else if (tmpReceiver.connState.equals(ConnState.FILE_NOT_EXISTS)) {//.rpy文件不存在
            this.WriteBankLogLn("FTP服务器不存在文件" + ftpSet.downDir + "/" + downFileName);
            String errFileName = oriFileName + ".err";
            String errLocalFile = this.getTempFileDirectory() + File.separator + p_reqQryBat.reqBatchNO + "." + tempTransID.getNextIDStr() + ".err";
            ftpSet.downDir = ftpSet.errDir;
            this.WriteBankLogLn("尝试下载err文件" + ftpSet.downDir + "/" + errFileName + "至本地文件" + errLocalFile);
            tmpReceiver = ftpPtClient.downloadFile(errFileName, errLocalFile);
            if (tmpReceiver.connState.length() == 0 && tmpReceiver.isCompleted) {


                FileInputStream errFileStream = new FileInputStream(errLocalFile);
                InputStreamReader errStreamReader = new InputStreamReader(errFileStream, getCharset());
                BufferedReader errLineReader = new BufferedReader(errStreamReader);
                String line1 = null;
                String errLineTxt = null;
                line1 = errLineReader.readLine();
                if (line1 != null) {
                    errLineTxt = errLineReader.readLine();
                }
                errLineReader.close();
                errStreamReader.close();
                errFileStream.close();

                if (StringHelper.hasAnyChar(errLineTxt)) {
                    retAts.respCode = "0";
                    retAts.reqSeqID = p_reqQryBat.reqBatchNO;
                    retAts.respInfo = errLineTxt;
                    retAts.transState = "err+" + errLineTxt;
                    retAts.payInfoCode = errLineTxt;
                    retAts.writeBeforeDetail();
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = line1;
                }

            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "未回盘";
            }
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = tmpReceiver.connMsg;
        }

        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_reqQryBat.reqBatchNO;
        }
        if (retAts.respCode.equals("-1")) {
            retAts.writeBeforeDetail();
        }
        retAts.writeAfterDetail();
        return retAts;
    }
}
